package cn.yl.wechat.server.controller;


import cn.yl.api.server.result.Result;
import cn.yl.api.server.util.UrlUtils;

import cn.yl.api.server.util.WechatConfig;
import cn.yl.wechat.server.service.UserService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@Slf4j
@RestController
public class WechatController {

    @Autowired
    private final WechatConfig wechatConfig;

    @Autowired
    private UserService userService;

    public WechatController(WechatConfig wechatConfig) {
        this.wechatConfig = wechatConfig;
    }

    @GetMapping("/wxlogin")
    public void getCode(String code,String state, HttpServletResponse response) throws IOException {
        log.info("微信传递的code: {}", code);
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=%s&" +
                "secret=%s&" +
                "code=%s" +
                "&grant_type=authorization_code";
        String resultJson = UrlUtils.loadURL(String.format(url, wechatConfig.getAppid(), wechatConfig.getSecret(), code));
        log.info("resultJson: {}", resultJson);
        // 解析json
        long beginTime = System.currentTimeMillis();
        while (resultJson==null){
            try {
                Thread.sleep(10L);
                resultJson = UrlUtils.loadURL(String.format(url, wechatConfig.getAppid(), wechatConfig.getSecret(), code));
                log.info("resultJson: {}", resultJson);
                if (System.currentTimeMillis() - beginTime > 30000) {
                    return;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        HashMap<String, String> map = JSON.parseObject(resultJson, HashMap.class);

        String access_token = map.get("access_token").toString();
        String openid = map.get("openid");
        userService.getJwtByWechat(access_token, openid, state);
        response.sendRedirect(wechatConfig.getSuccessUrl());
    }

//    @GetMapping("testwx")
//    public String testwx(){
//        String jwtByWechat = userService.getJwtByWechat("access_token", "openid");
//        return jwtByWechat;
//    }
}
